package com.sen.paydemo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者: 韩宗森
 * @创建时间: 2024/1/12 14:39
 */
public class WeixinUtil {

    //获取access_token
    public  static  String getAccessToken(){
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/token?");
        url.append("grant_type=");//grant_type设置
        url.append("client_credential");
        url.append("&appid=");//appid设置
        url.append("appid");//填写自己的公众号APPID
        url.append("&secret=");//secret设置
        url.append("secret");//secret
        Map<String, Object> resMap = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);//打印返回的信息
            JSONObject res = JSONObject.parseObject(content);//把信息封装为json*/
            //把信息封装到map
            // 使用Fastjson  JSON转换为Map
            // 将 JSONObject 转换为 Map
            resMap = (Map<String, Object>) res.toJavaObject(Map.class);

            System.out.println(resMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap.get("access_token").toString();

    }
    //获取ticket
    public  static  String getJsApiTicket(String accessToken){
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/ticket/getticket?");
        url.append("access_token=");//code设置
        url.append(accessToken);//获取的access_token
        url.append("&type=");//appid设置
        url.append("jsapi");

        Map<String, Object> map = new HashMap<>();
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);//打印返回的信息

            // 直接字符串转换为Map对象
            map = JSON.parseObject(content, Map.class);



            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map.get("ticket").toString();

    }

}
